/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：呼叫中心-业务逻辑层-工作台-接口实现
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taiping.cc.platform.service.impl;

import com.taiping.cc.application.constant.exception.ErrorStatusEnum;
import com.taipingframework.boot.cache.core.CommonCacheHandler;
import com.taipingframework.utility.exception.SystemInterrupterException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class RedisLockTest implements Runnable {

    private static Integer baseNum = 0;
    private CountDownLatch countDownLatch;
    private CommonCacheHandler cacheHandler;

    public RedisLockTest(CountDownLatch countDownLatch, CommonCacheHandler cacheHandler) {
        this.countDownLatch = countDownLatch;
        this.cacheHandler = cacheHandler;
    }

    @Override
    public void run() {
//CHECKSTYLE:OFF
        String redisLockValue = null;
        try {
            // 获取锁
            redisLockValue = cacheHandler.getRedisLock(5000, 3000);
            if (Objects.isNull(redisLockValue)) {
                throw new SystemInterrupterException(ErrorStatusEnum.UNABLE_GET_DISTRIBUTED_LOCKS);
            }

            baseNum += 1;
            String result = Thread.currentThread().getName() + " : " + new Date() + " ---> baseNum = " + baseNum;
            System.out.println(result);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            if (Objects.nonNull(redisLockValue)) {
                // 释放锁
                cacheHandler.releaseRedisLock(redisLockValue);
            }
            countDownLatch.countDown();
        }
//CHECKSTYLE:ON
    }

}
